#!/bin/bash
# --------------------------
# desc:
#     工具功能类
# author:
#     dockerlin@163.com
# --------------------------

#
# 检查该功能类依赖函数，所有依赖都检查
#
function tools_cxl(){
    #logger_debug "dirtool_cxl checking"
    local status=0
    return $status
}
#
# 执行命令行，统计脚本时间，返回执行结果
#
function cxlib_eval_command(){
    if [ -z "$1" ]; then return 1; fi
    logger_debug "准备执行命令 $1"
    startTime_s=`date +%s`

    local status=1
    local resultFile=`mktemp resultXXXXXX.txt`
    logger_debug "生成临时文件 $resultFile"
    # 2>&1错误也打印出来
    local cmdLine="$1 >$resultFile  2>&1"
    eval "$cmdLine" 
    status=$?
    [ $status -gt 0 ] && logger_error "执行命令 [$cmdLine] 报错，返回值 $status"
    # 文件不为空
    if [ -s "$resultFile" ]
    then 
        local result=`cat $resultFile`
        logger_info "执行结果 ：$result"  
        if [ -n "$2" ] && [ -f "$2" ] ; then echo -e "$result" > $2 ; fi  
    fi
    rm $resultFile -rf
    logger_debug "删除临时文件 $resultFile"
    endTime_s=`date +%s`
    sumTime=$[ $endTime_s - $startTime_s ]
    logger_info "命令 $1 执行完毕，花费 $sumTime 秒"
    unset startTime_s endTime_s sumTime
    return $status
}

# ----------------------------
# 执行mysql命令行并返回结果
# ----------------------------
cxlib_eval_mysql(){
    if [ -z "$1" ]; then return 1; fi
    if [ -z "$2" ]; then return 1; fi
    if [ -z "$3" ]; then return 2; fi
    if [ -z "$4" ]; then return 3; fi
    local status=1
    local cmdLine="mysql -u'$1' -p'$2' -h "$3" --local-infile=1 -e \"$4\"" 
    local file=""
    if [ -n "$5" ] && [ -f "$5" ]; then file=$5; fi
    #echo "in emic_eval_mysql"
    cxlib_eval_command "$cmdLine" "$file" && status=0 || status=1 
    return $status
}